package com.es.esapi.utils;

import com.alibaba.fastjson.JSON;
import com.es.esapi.domain.ClassA;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.io.RandomAccessRead;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.pdfbox.text.PDFTextStripperByArea;
import org.fit.pdfdom.PDFDomTree;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class pdf_solve_Main {
    //设置python程序的位置
    private static final String PATH = "C://Users//86198//Desktop//pdf_solve//ocr_PaddleOCR.py";

    public static List<ClassA> run(String fileName) throws Exception {
        System.out.println("开始处理");
        PdfConvertUtil pdftotxt = new PdfConvertUtil();
        pdftotxt.readPdfTextTest(fileName);

        List<ClassA> tlist=readTextImage(fileName);

        txttojson txtjson = new txttojson();
        return tlist;

    }




    public void pdftohtml(byte[] bytes, String htmlPath) throws Exception {
        //加载PDF文档
        PDDocument document = PDDocument.load(bytes);
        // 输出pdf文本
//        readText(document);
        //将字节流转换成字符流
        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(htmlPath)), "UTF-8"));
        //实例化pdfdom树对象
        PDFDomTree pdfDomTree = new PDFDomTree();
        //开始写入html文件
        pdfDomTree.writeText(document, out);
        //在文件末尾写入要引入的js，因为我将转换的html文件放在了webapp/pdfhtml文件夹下，所以这两个js文件也要放在pdfhtml文件夹下
        out.write("<script src=\"https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js />");
        out.flush();
        out.close();
        document.close();
    }


    public void readText(PDDocument document) throws IOException {
        PDFTextStripper stripper = new PDFTextStripper();
        String text = stripper.getText(document);
    }

    /*
    将文件转换为byte数组
     */
    private byte[] getBytes(String filePath) {
        byte[] buffer = null;
        try {
            File file = new File(filePath);
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }

    /**
     * 一次获取整个文件的内容
     *
     * @throws Exception
     */
    public static void readFile(String fileName) throws Exception {
        File file = new File(fileName);
        RandomAccessFile is = new RandomAccessFile(file, "r");
        PDFParser parser = new PDFParser((RandomAccessRead) is);
        parser.parse();
        PDDocument doc = parser.getPDDocument();
        PDFTextStripper textStripper = new PDFTextStripper();
        String s = textStripper.getText(doc);
        doc.close();
    }

    /**
     * 分页获取文字的内容
     *
     * @throws Exception
     */
    public static void readPage(String fileName) throws Exception {
        File file = new File(fileName);
        RandomAccessFile is = new RandomAccessFile(file, "r");
        PDFParser parser = new PDFParser((RandomAccessRead) is);
        parser.parse();
        PDDocument doc = parser.getPDDocument();
        PDFTextStripper textStripper = new PDFTextStripper();
        for (int i = 1; i <= doc.getNumberOfPages(); i++) {
            textStripper.setStartPage(i);
            textStripper.setEndPage(i);
            // 一次输出多个页时，按顺序输出
            textStripper.setSortByPosition(true);
            String s = textStripper.getText(doc);
        }
        doc.close();
    }
    /**
     * ocr识别图片
     *
     * @throws Exception
     */
    public static void testProcessBuilder(String img_path) throws IOException
    {
        String path=PATH;
        final ProcessBuilder processBuilder = new ProcessBuilder("python", path,img_path);
        processBuilder.redirectErrorStream(true);
        final Process process = processBuilder.start();
        final BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line = null;
        String result=null;
        int i=0;
        while ((line = reader.readLine()) != null)
        {
            result=result+line;
            i++;

        }
        List<String> Imglist=new ArrayList<String>();
        Imglist=extractMessageByRegular(result);
    }
    /**
     * 正则提取python返回数据。返回一个列表
     *
     * @throws Exception
     */
    public static List extractMessageByRegular(String msg){

        List<String> list=new ArrayList<String>();
        Pattern p = Pattern.compile("\\('(.*?)',");
        Matcher m = p.matcher(msg);
        while(m.find()){
            list.add(m.group().substring(1, m.group().length()-1));
        }
        return list;
    }
    /**
     * 读取文本内容和图片
     *
     * @return
     * @throws Exception
     */
    public static List<ClassA> readTextImage(String fileName) throws Exception {
        File file = new File(fileName);
        PDDocument doc = PDDocument.load(file);
        PDFTextStripper textStripper = new PDFTextStripper();
        List<ClassA> tlist = new ArrayList<ClassA>();
        txttojson name = new txttojson();

         String filename= name.getfilename(fileName);
        for (int i = 1; i <= doc.getNumberOfPages(); i++) {
            textStripper.setStartPage(i);
            textStripper.setEndPage(i);
            String s = textStripper.getText(doc);
            //存放bean对象

            //JSON.toJSONString()方法：将对象数组（JSON格式的字符串也可以）转换成JSON数据。

            // 读取图片
            PDPage page = doc.getPage(i - 1);
            PDResources resources = page.getResources();
            // 获取页中的对象
            ClassA classA = new ClassA();
            classA.setContent(s);

            Iterable<COSName> xobjects = resources.getXObjectNames();
            if (xobjects != null) {
                Iterator<COSName> imageIter = xobjects.iterator();
                while (imageIter.hasNext()) {
                    COSName cosName = imageIter.next();
                    boolean isImageXObject = resources.isImageXObject(cosName);
                    if (isImageXObject) {
                        // 获取每页资源的图片
                        PDImageXObject ixt = (PDImageXObject) resources.getXObject(cosName);
                        File outputfile = new File("C://solve//images//"+filename+"_"+"第 " + (i) + " 页" + cosName.getName() + ".jpg");
                        //创建新文件
                        classA.setPage(i);
                        classA.setImgpath("C://solve//images//"+filename+"_"+"第 " + (i) + " 页" + cosName.getName() + ".jpg");
                        ImageIO.write(ixt.getImage(), "jpg", outputfile);
                        testProcessBuilder("C://solve//images//"+filename+"_"+"第 " + (i) + " 页" + cosName.getName() + ".jpg");
                    }
                }
            }
            tlist.add(classA);

        }
        System.out.println("readTextImage");
        System.out.println(tlist);
        String json = JSON.toJSONString(tlist);
        //创建新文件
        PdfConvertUtil in =new PdfConvertUtil();
        File txtToJson = new File("C://solve//JSONImg//"+in.gettime()+".json");
        txtToJson.createNewFile();
        BufferedWriter out = new BufferedWriter(new FileWriter(txtToJson));
        out.write(json);
        out.flush(); // 把缓存区内容压入文件
        out.close(); // 最后记得关闭文件
        doc.close();
        return tlist;
    }

    /**
     * 区域解析
     *
     * @throws Exception
     */
    public static void readRectangle(String fileName) throws Exception {
        String filePath = fileName;
        File file = new File(filePath);
        PDDocument doc = PDDocument.load(file);
        // 这个四边形所在区域在 y轴向下为正，x轴向右为正。
        int x = 35;
        int y = 300;
        int width = 50;
        int height = 50;
        PDFTextStripperByArea stripper = new PDFTextStripperByArea();
        stripper.setSortByPosition(true);
        // 划定区域
        Rectangle2D rect = new Rectangle(x, y, width, height);
        stripper.addRegion("area", rect);
        PDPage page = doc.getPage(1);
        stripper.extractRegions(page);
        // 获取区域的text
        String data = stripper.getTextForRegion("area");
        data = data.trim();
        doc.close();
    }


    /*
    按页提取

     //String fileName: PDF路径;
     //int from:要读取得PDF开始页码；
     //int end:要读取得PDF结束页码；
     //每页之间分割字符串：“PDF解析第\d+页”
     */
}
